﻿using System;
using System.IO;
using System.Net;
using MaxStoreErp.Core.Exceptions;

namespace MaxStoreErp.Core.Ui.Drop
{
    public class DroppedFileHelper
    {
        public static byte[] GetDroppedFile(DropItem dropItem, string tempFolder)
        {
            switch (dropItem.DroppedItemType)
            {
                case FileSource.Local:
                {
                    return LoadFile(dropItem.DroppedItemSource);
                }
                case FileSource.WebLink:
                {
                    return GetFileFromWeb(new Uri(dropItem.DroppedItemSource), tempFolder);
                }
                default:
                    throw new ErpRuntimeException(
                        "Не удалось определить источник перетаскиваемого элемента!");
            }
        }

        static byte[] LoadFile(string fileName)
        {
            using (
                var reader =
                    new BinaryReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)))
            {
                var imageBytes = new byte[reader.BaseStream.Length];
                imageBytes = reader.ReadBytes(imageBytes.Length);
                reader.Close();
                return imageBytes;
            }
        }

        static byte[] GetFileFromWeb(Uri imageUri, string tempFolder)
        {
            var fileExt = Path.GetExtension(imageUri.AbsoluteUri);
            var tempFileName = Path.Combine(tempFolder, string.Format("{0}{1}", Guid.NewGuid(), fileExt));
            using (var webClient = new WebClient())
            {
                webClient.DownloadFile(imageUri, tempFileName);
            }

            return LoadFile(tempFileName);
        }
    }
}
